package com.stud.framework.web.service;

import com.stud.common.enums.RoleEnum;
import com.stud.common.jdbc.MyJdbcTemplate;
import com.stud.system.service.SysRoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.stud.common.core.domain.entity.SysUser;
import com.stud.common.core.domain.model.LoginUser;
import com.stud.common.enums.UserStatus;
import com.stud.common.exception.ServiceException;
import com.stud.common.utils.StringUtils;
import com.stud.system.service.SysUserService;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Set;

/**
 * 用户验证处理 实现了org.springframework.security.core.userdetails.UserDetailsService,并且重写了其loadUserByUsername,
 * 所以登录时springSecurity会通过loadUserByUsername获取用户信息
 *
 * @author Stud
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private MyJdbcTemplate jdbcTemplate;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = userService.selectUserByUserName(username);
        if (StringUtils.isNull(user)) {
            log.info("登录用户：{} 不存在.", username);
            throw new ServiceException("登录用户：" + username + " 不存在");
        } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            log.info("登录用户：{} 已被删除.", username);
            throw new ServiceException("对不起，您的账号：" + username + " 已被删除");
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new ServiceException("对不起，您的账号：" + username + " 已停用");
        }

        passwordService.validate(user);

        if (sysRoleService.checkRole(user.getUserId(), RoleEnum.ADMIN)) {
            user.setAdmin(true);
        }

        if (!sysRoleService.checkRole(user.getUserId(), RoleEnum.ADMIN, RoleEnum.PROJECT)) {
            //如果不是管理员,就查询关联的项目ID集合,用于后续业务筛选
            String projectSql = " select project_id from t_user_project_link where user_id = ? and del_flag = 0 ";
            List<Long> projectIdList = jdbcTemplate.selectSingleColumn(projectSql, Long.class, user.getUserId());
            if (CollectionUtils.isEmpty(projectIdList)) {
                projectIdList.add(-1L);
            }
            user.setProjectIdList(projectIdList);

            Set<String> roleKeys = sysRoleService.selectRoleKeysByUserId(user.getUserId());
            user.setRoleKeys(roleKeys);
        }

        return createLoginUser(user);
    }

    public UserDetails createLoginUser(SysUser user) {
        LoginUser loginUser = new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
        return loginUser;
    }
}
